package fm.admin.controller;

import fm.controller.BaseController;
import fm.dto.NeiyiUser;
import fm.entity.AccountBalance;
import fm.entity.CashApplication;
import fm.entityEnum.CrashStatusEnum;
import fm.exception.BizException;
import fm.nio.SemaphoreExecutor;
import fm.yichenet.service.AccountBalanceService;
import fm.yichenet.service.CashApplicationService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * Created by CM on 2017/6/29.
 */
@Controller
@RequestMapping("/cash/application/mgr")
public class CashApplicationMgrController extends BaseController {

    @Autowired
    CashApplicationService cashApplicationService;
    @Autowired
    fm.mongoService.UserService userService;
    @Autowired
    AccountBalanceService accountBalanceService;


    private SemaphoreExecutor executor = new SemaphoreExecutor(50, "fillCashOrderInfo");


    @RequestMapping("/index")
    public String index(ModelMap modelMap) {

        return "/admin/cash/index";
    }

    @ResponseBody
    @RequestMapping("/list")
    public Map getCashApplicationList(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      String userId, String startTime, String endTime, CrashStatusEnum status
    ) {
        Map res = new HashMap();
        try {
            List<CashApplication> cps = cashApplicationService.getUserCashApplications(userId, startTime, endTime, status, pageNum, pageSize);
            long total = cashApplicationService.countUserCashApplications(userId, startTime, endTime, status);

            final List<Map> data = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(cps)) {
                final CountDownLatch cdl = new CountDownLatch(cps.size());
                for (final CashApplication cp : cps) {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                String userId = cp.getWxUserId();
                                AccountBalance ab = accountBalanceService.addOrGetBalance(userId);
                                NeiyiUser user = userService.getById(userId);

                                Map dataItem = new HashMap();
                                dataItem.put("cp", cp);
                                dataItem.put("ab", ab);
                                dataItem.put("us", user);

                                data.add(dataItem);

                            } catch (Exception ex) {
                                LOGGER.error("请求账户信息发生错误！", ex);
                            } finally {
                                cdl.countDown();
                            }

                        }
                    });
                }
                cdl.await();
            }
            res.put("data", data);
            res.put("total", total);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/apply")
    public Map applyCashApplication(Long applicationId, String remark) {
        Map res = new HashMap();
        try {
            cashApplicationService.applyApplication(applicationId, remark);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/refuse")
    public Map refuseCashApplication(Long applicationId, String remark) {
        Map res = new HashMap();
        try {
            cashApplicationService.refuseApplication(applicationId, remark);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

}
